package JVM.JMX;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;

public class Client {

    public static void main(String[] args) throws IOException, Exception, NullPointerException {
        JMXServiceURL url = new JMXServiceURL
                ("service:jmx:rmi:///jndi/rmi://xx:10086/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        //ObjectName的名称与前面注册时候的保持一致
        ObjectName mbeanName = new ObjectName("java.lang:type=OperatingSystem");
        //获取指定Mbean的特定属性值
        String arch = (String) mbsc.getAttribute(mbeanName, "Arch");
        String name = (String) mbsc.getAttribute(mbeanName, "Name");
        int AvailableProcessors = (int) mbsc.getAttribute(mbeanName, "AvailableProcessors");
        double SystemLoadAverage = (double) mbsc.getAttribute(mbeanName, "SystemLoadAverage");
        String Version = (String) mbsc.getAttribute(mbeanName, "Version");
        double ProcessCpuLoad = (double) mbsc.getAttribute(mbeanName, "ProcessCpuLoad");
        double SystemCpuLoad = (double) mbsc.getAttribute(mbeanName, "SystemCpuLoad");
        long TotalPhysicalMemorySize = (long) mbsc.getAttribute(mbeanName, "TotalPhysicalMemorySize");
        long FreePhysicalMemorySize = (long) mbsc.getAttribute(mbeanName, "FreePhysicalMemorySize");
        long ProcessCpuTimeme = (long) mbsc.getAttribute(mbeanName, "ProcessCpuTime");
        long FreeSwapSpaceSize = (long) mbsc.getAttribute(mbeanName, "FreeSwapSpaceSize");
        long TotalSwapSpaceSize = (long) mbsc.getAttribute(mbeanName, "TotalSwapSpaceSize");
        long CommittedVirtualMemorySize = (long) mbsc.getAttribute(mbeanName, "CommittedVirtualMemorySize");
        // 打印
        System.out.println("操作系统名称: " + name);
        System.out.println("CPU架构: " + arch);
        System.out.println("最大可用的处理器数量: " + AvailableProcessors);
        System.out.println("系统负载平均值: " + SystemLoadAverage);
        System.out.println("操作系统版本: " + Version);
        System.out.println("JVM进程的CPU负载: " + ProcessCpuLoad);
        System.out.println("整个系统的CPU使用率: " + SystemCpuLoad);
        System.out.println("物理内存总量: " + TotalPhysicalMemorySize);
        System.out.println("可用物理内存量: " + FreePhysicalMemorySize);
        System.out.println("JVM进程使用的CPU时间: " + ProcessCpuTimeme);
        System.out.println("系统可用交换空间: " + FreeSwapSpaceSize);
        System.out.println("交换空间总量: " + TotalSwapSpaceSize);
        System.out.println("保证可供运行进程使用的虚拟内存量: " + CommittedVirtualMemorySize);
    }
}

